<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" open-type="getUserInfo" @click="getUserInfo">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">
			<text>登录后尽享更多权益</text>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		methods: {
			...mapMutations('userInfo', ['setUserInfo','setToken']),
			getUserInfo(e) {
				let that = this
				uni.getUserProfile({
					desc: 'asdasdasd',
					success(e) {
						console.log(e);
						that.setUserInfo(e)
						that.getToken(e)
					},
					fail(e) {
						return uni.showToast({
							title: '您取消了登录授权!',
							duration: 1500,
							icon: 'none',
						})
					}
				})
			},
			async getToken(obj) {
				const [err, res] = await uni.login().catch(err => err)
				if (err || res.errMsg !== 'login:ok') return uni.showToast({
					title: '登录失败!',
					duration: 1500,
					icon: 'none',
				})
				
				let {
					code
				} = res
				let {
					encryptedData,
					iv,
					rawData,
					signature
				} = obj
				let  query = {
					code,
					encryptedData,
					iv,
					rawData,
					signature
				}
				// 换取 token
				const {
					data: loginResult
				} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				console.log(loginResult);
				this.setToken('aslckajslkcjaslkcalskjcalsjcalks')
			}
		}
	}
</script>

<style lang="scss">
	.login-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding-top: 80px;

		.btn-login {
			width: 90%;
			border-radius: 999px;
			margin: 5px 0;
		}

		.tips-text {
			width: 70%;
			font-size: 12px;
			color: #999;
			text-align: center;
			background-image: linear-gradient(to bottom, #fff, #fff 46%, #ccc 46%, #ccc 54%, #fff 54%, #fff);

			text {
				background-color: #fff;
				padding: 0 10px;
			}
		}
	}
</style>
